package com.ruoyi.common.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.CollectionUtils;
import com.ruoyi.common.utils.StrUtils;
import com.ruoyi.common.utils.http.OkHttpUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @author : hcl
 * @Date : 2023/8/7
 * 异常通知
 */
@Slf4j
public class HookNotification {
    private final String url;

    /**
     * @param url webhook url
     */
    public HookNotification(String url) {
        this.url = url;
    }

    public void error(String err) {
        log.error("异常通知: {}", err);
        try {
            sendMessage(err, null);
        } catch (Exception e) {
            log.error("web_hook_err: {}", e.getMessage());
        }
    }

    private void sendMessage(String errMsg, String mobileList) throws Exception {
        if (StrUtils.isNotBlank(this.url)) {
            OkHttpUtils.getInstance().postJsonAsyn(this.url, textBody(errMsg, mobileList), null);
        }
    }

    /**
     * @param content    发送消息
     * @param mobileList 手机号列表
     */
    private String textBody(String content, String mobileList) {
        Map<String, Object> body = new HashMap<>();
        body.put("msgtype", "text");
        body.put("text", text(content, null));
        return JSONUtil.toJsonStr(body);
    }

    private Map<String, Object> text(String content, String mobileList) {
        Map<String, Object> text = new HashMap<>();
        text.put(Constants.CONTENT, content);
        if (StrUtil.isNotBlank(mobileList)) {
            text.put(Constants.MENTIONED_MOBILE_LIST, CollectionUtils.parseLongSet(mobileList));
        }
        return text;
    }

    public static void main(String[] args) {
        HookNotification hook = new HookNotification("https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=c09b930a-01b9-4901-a95e-7fb524bd5dc5");
        hook.error("测试");
    }
}
